{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n# Customizing Figure Layouts Using GridSpec and Other Functions\n\n\nHow to create grid-shaped combinations of axes.\n\n    :func:`~matplotlib.pyplot.subplots`\n        Perhaps the primary function used to create figures and axes.\n        It's also similar to :func:`.matplotlib.pyplot.subplot`,\n        but creates and places all axes on the figure at once.  See also\n        `matplotlib.Figure.subplots`.\n\n    :class:`~matplotlib.gridspec.GridSpec`\n        Specifies the geometry of the grid that a subplot will be\n        placed. The number of rows and number of columns of the grid\n        need to be set. Optionally, the subplot layout parameters\n        (e.g., left, right, etc.) can be tuned.\n\n    :class:`~matplotlib.gridspec.SubplotSpec`\n        Specifies the location of the subplot in the given *GridSpec*.\n\n    :func:`~matplotlib.pyplot.subplot2grid`\n        A helper function that is similar to\n        :func:`~matplotlib.pyplot.subplot`,\n        but uses 0-based indexing and let subplot to occupy multiple cells.\n        This function is not covered in this tutorial.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Basic Quickstart Guide\n======================\n\nThese first two examples show how to create a basic 2-by-2 grid using\nboth :func:`~matplotlib.pyplot.subplots` and :mod:`~matplotlib.gridspec`.\n\nUsing :func:`~matplotlib.pyplot.subplots` is quite simple.\nIt returns a :class:`~matplotlib.figure.Figure` instance and an array of\n:class:`~matplotlib.axes.Axes` objects.\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "fig1, f1_axes = plt.subplots(ncols=2, nrows=2, constrained_layout=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For a simple use case such as this, :mod:`~matplotlib.gridspec` is\nperhaps overly verbose.\nYou have to create the figure and :class:`~matplotlib.gridspec.GridSpec`\ninstance separately, then pass elements of gridspec instance to the\n:func:`~matplotlib.figure.Figure.add_subplot` method to create the axes\nobjects.\nThe elements of the gridspec are accessed in generally the same manner as\nnumpy arrays.\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "fig2 = plt.figure(constrained_layout=True)\nspec2 = gridspec.GridSpec(ncols=2, nrows=2, figure=fig2)\nf2_ax1 = fig2.add_subplot(spec2[0, 0])\nf2_ax2 = fig2.add_subplot(spec2[0, 1])\nf2_ax3 = fig2.add_subplot(spec2[1, 0])\nf2_ax4 = fig2.add_subplot(spec2[1, 1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The power of gridspec comes in being able to create subplots that span\nrows and columns.  Note the\n`Numpy slice <https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html>`_\nsyntax for selecting the part of the gridspec each subplot will occupy.\n\nNote that we have also used the convenience method `.Figure.add_gridspec`\ninstead of `.gridspec.GridSpec`, potentially saving the user an import,\nand keeping the namespace cleaner.\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "fig3 = plt.figure(constrained_layout=True)\ngs = fig3.add_gridspec(3, 3)\nf3_ax1 = fig3.add_subplot(gs[0, :])\nf3_ax1.set_title('gs[0, :]')\nf3_ax2 = fig3.add_subplot(gs[1, :-1])\nf3_ax2.set_title('gs[1, :-1]')\nf3_ax3 = fig3.add_subplot(gs[1:, -1])\nf3_ax3.set_title('gs[1:, -1]')\nf3_ax4 = fig3.add_subplot(gs[-1, 0])\nf3_ax4.set_title('gs[-1, 0]')\nf3_ax5 = fig3.add_subplot(gs[-1, -2])\nf3_ax5.set_title('gs[-1, -2]')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ":mod:`~matplotlib.gridspec` is also indispensable for creating subplots\nof different widths via a couple of methods.\n\nThe method shown here is similar to the one above and initializes a\nuniform grid specification,\nand then uses numpy indexing and slices to allocate multiple\n\"cells\" for a given subplot.\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "fig4 = plt.figure(constrained_layout=True)\nspec4 = fig4.add_gridspec(ncols=2, nrows=2)\nanno_opts = dict(xy=(0.5, 0.5), xycoords='axes fraction',\n                 va='center', ha='center')\n\nf4_ax1 = fig4.add_subplot(spec4[0, 0])\nf4_ax1.annotate('GridSpec[0, 0]', **anno_opts)\nfig4.add_subplot(spec4[0, 1]).annotate('GridSpec[0, 1:]', **anno_opts)\nfig4.add_subplot(spec4[1, 0]).annotate('GridSpec[1:, 0]', **anno_opts)\nfig4.add_subplot(spec4[1, 1]).annotate('GridSpec[1:, 1:]', **anno_opts)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Another option is to use the ``width_ratios`` and ``height_ratios``\nparameters. These keyword arguments are lists of numbers.\nNote that absolute values are meaningless, only their relative ratios\nmatter. That means that ``width_ratios=[2, 4, 8]`` is equivalent to\n``width_ratios=[1, 2, 4]`` within equally wide figures.\nFor the sake of demonstration, we'll blindly create the axes within\n``for`` loops since we won't need them later.\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "fig5 = plt.figure(constrained_layout=True)\nwidths = [2, 3, 1.5]\nheights = [1, 3, 2]\nspec5 = fig5.add_gridspec(ncols=3, nrows=3, width_ratios=widths,\n                          height_ratios=heights)\nfor row in range(3):\n    for col in range(3):\n        ax = fig5.add_subplot(spec5[row, col])\n        label = 'Width: {}\\nHeight: {}'.format(widths[col], heights[row])\n        ax.annotate(label, (0.1, 0.5), xycoords='axes fraction', va='center')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Learning to use ``width_ratios`` and ``height_ratios`` is particularly\nuseful since the top-level function :func:`~matplotlib.pyplot.subplots`\naccepts them within the ``gridspec_kw`` parameter.\nFor that matter, any parameter accepted by\n:class:`~matplotlib.gridspec.GridSpec` can be passed to\n:func:`~matplotlib.pyplot.subplots` via the ``gridspec_kw`` parameter.\nThis example recreates the previous figure without directly using a\ngridspec instance.\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "gs_kw = dict(width_ratios=widths, height_ratios=heights)\nfig6, f6_axes = plt.subplots(ncols=3, nrows=3, constrained_layout=True,\n        gridspec_kw=gs_kw)\nfor r, row in enumerate(f6_axes):\n    for c, ax in enumerate(row):\n        label = 'Width: {}\\nHeight: {}'.format(widths[c], heights[r])\n        ax.annotate(label, (0.1, 0.5), xycoords='axes fraction', va='center')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The ``subplots`` and ``gridspec`` methods can be combined since it is\nsometimes more convenient to make most of the subplots using ``subplots``\nand then remove some and combine them.  Here we create a layout with\nthe bottom two axes in the last column combined.\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "fig7, f7_axs = plt.subplots(ncols=3, nrows=3)\ngs = f7_axs[1, 2].get_gridspec()\n# remove the underlying axes\nfor ax in f7_axs[1:, -1]:\n    ax.remove()\naxbig = fig7.add_subplot(gs[1:, -1])\naxbig.annotate('Big Axes \\nGridSpec[1:, -1]', (0.1, 0.5),\n               xycoords='axes fraction', va='center')\n\nfig7.tight_layout()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Fine Adjustments to a Gridspec Layout\n=====================================\n\nWhen a GridSpec is explicitly used, you can adjust the layout\nparameters of subplots that are created from the GridSpec.  Note this\noption is not compatible with ``constrained_layout`` or\n`.Figure.tight_layout` which both adjust subplot sizes to fill the\nfigure.\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "fig8 = plt.figure(constrained_layout=False)\ngs1 = fig8.add_gridspec(nrows=3, ncols=3, left=0.05, right=0.48, wspace=0.05)\nf8_ax1 = fig8.add_subplot(gs1[:-1, :])\nf8_ax2 = fig8.add_subplot(gs1[-1, :-1])\nf8_ax3 = fig8.add_subplot(gs1[-1, -1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is similar to :func:`~matplotlib.pyplot.subplots_adjust`, but it only\naffects the subplots that are created from the given GridSpec.\n\nFor example, compare the left and right sides of this figure:\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "fig9 = plt.figure(constrained_layout=False)\ngs1 = fig9.add_gridspec(nrows=3, ncols=3, left=0.05, right=0.48,\n                        wspace=0.05)\nf9_ax1 = fig9.add_subplot(gs1[:-1, :])\nf9_ax2 = fig9.add_subplot(gs1[-1, :-1])\nf9_ax3 = fig9.add_subplot(gs1[-1, -1])\n\ngs2 = fig9.add_gridspec(nrows=3, ncols=3, left=0.55, right=0.98,\n                        hspace=0.05)\nf9_ax4 = fig9.add_subplot(gs2[:, :-1])\nf9_ax5 = fig9.add_subplot(gs2[:-1, -1])\nf9_ax6 = fig9.add_subplot(gs2[-1, -1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "GridSpec using SubplotSpec\n==========================\n\nYou can create GridSpec from the :class:`~matplotlib.gridspec.SubplotSpec`,\nin which case its layout parameters are set to that of the location of\nthe given SubplotSpec.\n\nNote this is also available from the more verbose\n`.gridspec.GridSpecFromSubplotSpec`.\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "fig10 = plt.figure(constrained_layout=True)\ngs0 = fig10.add_gridspec(1, 2)\n\ngs00 = gs0[0].subgridspec(2, 3)\ngs01 = gs0[1].subgridspec(3, 2)\n\nfor a in range(2):\n    for b in range(3):\n        fig10.add_subplot(gs00[a, b])\n        fig10.add_subplot(gs01[b, a])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A Complex Nested GridSpec using SubplotSpec\n===========================================\n\nHere's a more sophisticated example of nested GridSpec where we put\na box around each cell of the outer 4x4 grid, by hiding appropriate\nspines in each of the inner 3x3 grids.\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import numpy as np\nfrom itertools import product\n\n\ndef squiggle_xy(a, b, c, d, i=np.arange(0.0, 2*np.pi, 0.05)):\n    return np.sin(i*a)*np.cos(i*b), np.sin(i*c)*np.cos(i*d)\n\n\nfig11 = plt.figure(figsize=(8, 8), constrained_layout=False)\n\n# gridspec inside gridspec\nouter_grid = fig11.add_gridspec(4, 4, wspace=0.0, hspace=0.0)\n\nfor i in range(16):\n    inner_grid = outer_grid[i].subgridspec(3, 3, wspace=0.0, hspace=0.0)\n    a, b = int(i/4)+1, i % 4+1\n    for j, (c, d) in enumerate(product(range(1, 4), repeat=2)):\n        ax = fig11.add_subplot(inner_grid[j])\n        ax.plot(*squiggle_xy(a, b, c, d))\n        ax.set_xticks([])\n        ax.set_yticks([])\n        fig11.add_subplot(ax)\n\nall_axes = fig11.get_axes()\n\n# show only the outside spines\nfor ax in all_axes:\n    for sp in ax.spines.values():\n        sp.set_visible(False)\n    if ax.is_first_row():\n        ax.spines['top'].set_visible(True)\n    if ax.is_last_row():\n        ax.spines['bottom'].set_visible(True)\n    if ax.is_first_col():\n        ax.spines['left'].set_visible(True)\n    if ax.is_last_col():\n        ax.spines['right'].set_visible(True)\n\nplt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "------------\n\nReferences\n\"\"\"\"\"\"\"\"\"\"\n\nThe usage of the following functions and methods is shown in this example:\n\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "matplotlib.pyplot.subplots\nmatplotlib.figure.Figure.add_gridspec\nmatplotlib.figure.Figure.add_subplot\nmatplotlib.gridspec.GridSpec\nmatplotlib.gridspec.SubplotSpec.subgridspec\nmatplotlib.gridspec.GridSpecFromSubplotSpec"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
